import config from '@/config/env.js'

function Request() {
  function http(url, data, option = { header: {}, showError: true }, method = "GET") {
    return new Promise((resolve, reject) => {
      //创建ajax对象
      uni.request({
        url: config.baseUrl + url, //仅为示例，并非真实接口地址。
        data,
        header: {
          ...option.header
        },
        method,
        success: (res) => {
          resolve(res.data)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  }

  this.post = (url, data, option) => http(url, data, option, "POST")
  this.get = (url, data, option) => http(url, data, option, "GET")
  this.delete = (url, data, option) => http(url, data, option, "DELETE")
  this.put = (url, data, option) => http(url, data, option, "PUT")
  this.request = (options) => {
    const { url, data, method, ...option } = options
    return http(url, data, option, method)
  }
  this.upload = (url, data, option) => {
    return new Promise((resolve, reject) => {
      //创建ajax对象
      uni.uploadFile({
        url: config.baseUrl + url, //仅为示例，并非真实接口地址。
        formData: option.data,
        header: {
          ...option.header
        },
        filePath: data.data,
        name: data.name || "file",
        success: (res) => {
          resolve(res.data)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  }
  this.download = (url, base = true) => {
    return new Promise((resolve, reject) => {
      uni.downloadFile({
        url: base ? baseUrl + url : url, //仅为示例，并非真实的资源
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(res)
          }
        },
        fail(err) {
          reject(err)
        }
      })
    })
  }
}



export default new Request()